package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

/**
 * @author hd
 */
@Data
@Slf4j
@Component
public class CacheClient {
    private final StringRedisTemplate  stringRedisTemplate;
    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public void set(String key, Object value, Long time,  TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }
    public void setWithLogicalExpire(String key, Object value, Long time,  TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
    }
    public <T,  V> T queryWithPassThrough(String keyPrefix, Class<T> type,V id, Long time,  TimeUnit unit,  Function<V, T> dbFallback) {
        String key=  keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        if (json != null) {
            return null;
        }
        T t = dbFallback.apply(id);
        if (t == null) {
            this.set(key, "", time, unit);
            return null;
        }
        this.set(key, t, time, unit);
        return t;
    }
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public <T,  V> T queryWithLogicalExpire(String keyPrefix, Class<T> type,V id,Function<V, T> dbFallback, Long time,  TimeUnit unit) {
        String  key=  keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        T t =JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            return t;
        }
        String lock = LOCK_SHOP_KEY + id;
        if (tryLock(lock)) {
            //获取锁成功，开启独立线程，实现缓存重建
            try {
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    T t1 =dbFallback.apply(id);
                    this.setWithLogicalExpire(key, t1,time,unit );
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                releaseLock(lock);
            }
        }
        return t;
    }
    private boolean tryLock(String key){
        Boolean flag =stringRedisTemplate.opsForValue().setIfAbsent(key, "1",LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }
    private void releaseLock(String key){
        stringRedisTemplate.delete(key);
    }
    public <T,  V> T queryWithMutex(String keyPrefix,V id,  Class<T> type,  Function<V, T> dbFallback,  Long nullTime,  TimeUnit unit,  Long time) {
        String  key=  keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        if (json != null) {
            return null;
        }
        //缓存重建
        //获取互斥锁
        //判断是否获取锁成功
        //失败获取锁，休眠并重试
        String lock = LOCK_SHOP_KEY + id;
        T t;
        try {
            if (!tryLock(lock)) {
                Thread.sleep(50);
                return queryWithMutex(keyPrefix,  id, type, dbFallback, nullTime,unit,time);
            }
            //获取锁成功，二次判断缓存是否存在
            json = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(json)) {
                return JSONUtil.toBean(json, type);
            }
            if (json != null) {
                return null;
            }
            //不存在，查询数据库
            t = dbFallback.apply(id);
            if (t == null) {
                this.set(key, "", nullTime, unit);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(t), time, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            releaseLock(lock);
        }
        return t;
    }
}
